//
//  AddExpenseViewController.m
//  Wallets Manager
//
//  Created by Tung Nguyen on 10/14/12.
//  Copyright (c) 2012 BKHN. All rights reserved.
//

#import "AddExpenseViewController.h"

@interface AddExpenseViewController ()
{
     NSDate *currentDate;
}
@end

@implementation AddExpenseViewController
@synthesize scrollVIew;
@synthesize headerLabel;
@synthesize expenseNameTextField;
@synthesize categoryTextField;
@synthesize categoryImageView;
@synthesize amountTextField;
@synthesize dateTextField;
@synthesize walletTextField;
@synthesize planTextField;
@synthesize addButton;
@synthesize planImageView;
@synthesize noteTextField;
@synthesize monthViewCalendar;
@synthesize pickerViewPopup;
@synthesize dateString;
@synthesize kindOfView;
@synthesize currentExpense;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //------------------Init plan and expense category to default-----------------//
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    walletTextField.text = delegate.currentWallet.w_name;
    
    currentExpenseType = [DataBaseAccess eTypeForName:@"Other"];
    currentPlan        = [DataBaseAccess planForName:@"Chưa có kế hoạch" andWallet:delegate.currentWallet];
    //--------------------Create Mask View--------------------------------//
    maskView1 = [[UIView alloc]initWithFrame:CGRectMake(6, 102, 309, 40)];
    maskView1.backgroundColor = [UIColor clearColor];
    [self.view addSubview:maskView1];
    [self.view bringSubviewToFront:maskView1];
    
    maskView2 = [[UIView alloc]initWithFrame:CGRectMake(6, 272, 309, 40)];
    maskView2.backgroundColor = [UIColor clearColor];
    [self.view addSubview:maskView2];
    [self.view bringSubviewToFront:maskView2];
    
    [scrollVIew setContentSize:CGSizeMake(320, 390)];
    scrollVIew.contentSize = CGSizeMake(320, 400);
    scrollVIew.scrollEnabled = YES;
    
    if([kindOfView isEqualToString:@"Edit"]) {
        headerLabel.text = @"Edit Expense";
        [addButton setTitle:@"Edit" forState:UIControlStateNormal];
        //------------Set Current Date + Plan = edited expense date+ plan----------//
        currentDate = currentExpense.e_date;
        currentPlan = currentExpense.eToPlan;
        
        expenseNameTextField.text = currentExpense.e_name;
        
        categoryTextField.text = currentExpense.eToExpenseType.et_name;
        [categoryImageView setImage:[UIImage imageNamed:currentExpense.eToExpenseType.et_image]];
        
        amountTextField.text = [NSString stringWithFormat:@"%d",[currentExpense.e_amount intValue]];
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"MM/dd/yyyy"];
        dateTextField.text = [dateFormatter stringFromDate:currentExpense.e_date];
            
        
        planTextField.text = currentExpense.eToPlan.p_name;
        [planImageView setImage:[UIImage imageNamed:currentExpense.eToPlan.p_image]];
        
        noteTextField.text = currentExpense.e_notes;
    }
}

-(void) viewWillAppear:(BOOL)animated {
    
    //--------------------------NSNotification Center-----------------------//
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getExpenseCategoryOnSuccess :) name:@"getExpenseCategoryOnSuccess" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getPlanFromExpenseViewOnSuccess: ) name:@"getPlanFromExpenseViewOnSuccess" object:nil];
}

-(void) viewDidAppear:(BOOL)animated {
    
//    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"getExpenseCategoryOnSuccess" object:nil];
//    
//     [[NSNotificationCenter defaultCenter]removeObserver:self name:@"getPlanFromExpenseViewOnSuccess" object:nil];
    
}
- (void)viewDidUnload
{
    [self setExpenseNameTextField:nil];
    [self setCategoryTextField:nil];
    [self setAmountTextField:nil];
    [self setDateTextField:nil];
    [self setWalletTextField:nil];
    [self setPlanTextField:nil];
    [self setPlanImageView:nil];
    [self setCategoryImageView:nil];
    [self setNoteTextField:nil];
    [self setScrollVIew:nil];
    [self setHeaderLabel:nil];
    [self setAddButton:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Touch Delegate
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
    UITouch *touch = [touches anyObject];
    CGPoint touchPosition = [touch locationInView:touch.view];
    
    if (touchPosition.y >=0 && touchPosition.y <=40) {
        if(touch.view == maskView1) {
            SelectExpenseCategory *selectExpenseCategory = [[SelectExpenseCategory alloc]init];
            [self.navigationController pushViewController:selectExpenseCategory  animated:YES];
        }else{
            SelectPlanViewController *selectPlanViewController = [[SelectPlanViewController alloc]init];
            selectPlanViewController.isFromView = @"Add Expense";
            [self.navigationController pushViewController:selectPlanViewController animated:YES];
        }   
    }
}

#pragma mark --------------------NSNotification Delegate-------------------

-(void) getExpenseCategoryOnSuccess : (NSNotification*)notification {
    NSDictionary *tempDict = [notification object];
    currentExpenseType = [tempDict objectForKey:@"key"];
    categoryTextField.text = currentExpenseType.et_name;
    [categoryImageView setImage:[UIImage imageNamed:currentExpenseType.et_image]];
    
}

-(void) getPlanFromExpenseViewOnSuccess :(NSNotification*)notification {
    NSDictionary *tempDict = [notification object];
    currentPlan = [tempDict objectForKey:@"key"];
    planTextField.text = currentPlan.p_name;
    [planImageView setImage:[UIImage imageNamed:currentPlan.p_image]];
}

#pragma mark ----------------------TextField Delegate-------------------
//-(void) textFieldDidBeginEditing:(UITextField *)textField {
//    if( textField == dateTextField) {
//        [self createDatePickerView];
//    }
//}
-(BOOL) textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

-(void) textFieldDidBeginEditing:(UITextField *)textField {
    if(textField == dateTextField) {
        [self createDatePickerView];
    }
}

#pragma mark ----------------------Calendar Delegate---------------------

- (void) createDatePickerView {
    
    if(pickerViewPopup == nil)
    {
        pickerViewPopup = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
        
        [pickerViewPopup setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
        
        //    datePickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 44, 0, 0)];
        //    datePickerView.datePickerMode = UIDatePickerModeDate;
        //    datePickerView.hidden = NO;
        //    datePickerView.date = [NSDate date];
        //    [datePickerView addTarget:self action:@selector(datePickerValueChanged :) forControlEvents:UIControlEventValueChanged];
        
        UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
        pickerToolbar.barStyle = UIBarStyleBlackOpaque;
        [pickerToolbar sizeToFit];
        
        NSMutableArray *barItems = [[NSMutableArray alloc] init];
        
        UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneDateButtonPressed:)];
        [barItems addObject:doneBtn];
        
        UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        [barItems addObject:flexSpace];
        
        UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelDateButtonPressed:)];
        [barItems addObject:cancelBtn];
        
        [pickerToolbar setItems:barItems animated:YES];
        
        if(monthViewCalendar == nil)
        {
            monthViewCalendar = [[TKCalendarMonthView alloc] initWithSundayAsFirst:NO];
            monthViewCalendar.delegate  = self;
            monthViewCalendar.dataSource = self;
            //NSLog(@"MONTH %f x %f", monthViewCalendar.bounds.size.width, monthViewCalendar.bounds.size.height);
            [monthViewCalendar reload];
        }
        [monthViewCalendar setFrame:CGRectMake(0, 44, 320, monthViewCalendar.bounds.size.height)];
        pickerViewPopup.clipsToBounds=YES;
        
        //[pickerViewPopup addSubview:datePickerView];
        
        [pickerViewPopup addSubview:pickerToolbar];
        [pickerViewPopup addSubview:monthViewCalendar];
        [pickerViewPopup setBounds:CGRectMake(0, 0, 320, 460)];
        [pickerViewPopup showInView:self.view];
        [self popUpRefreshFrame];
        
        //[self popUpRefreshFrame];
        
    }else
    {
        [pickerViewPopup showInView:self.view];
        [self popUpRefreshFrame];
    }
    
}

-(void)popUpRefreshFrame
{
    [UIView beginAnimations:@"resize_animation" context:NULL];
    [UIView setAnimationDuration:0.3];
    
    pickerViewPopup.clipsToBounds=YES;
    [pickerViewPopup setFrame:CGRectMake(0.0, 460 - monthViewCalendar.bounds.size.height - 44, 320, monthViewCalendar.bounds.size.height + 44)];
    
    [UIView commitAnimations];
    
    
}

- (NSArray*) calendarMonthView:(TKCalendarMonthView*)monthView marksFromDate:(NSDate*)startDate toDate:(NSDate*)lastDate{
	return nil;
}

-(void)calendarMonthView:(TKCalendarMonthView *)monthView didSelectDate:(NSDate *)date
{
    NSLog(@"%@", date);
    currentDate = date;
}

- (void) calendarMonthView:(TKCalendarMonthView*)monthView monthDidChange:(NSDate*)month animated:(BOOL)animated
{
    //NSLog(@"FRAME = %f X %f", monthView.frame.size.width , monthView.frame.size.height);
    [self performSelector:@selector(popUpRefreshFrame)];
}

-(void)doneDateButtonPressed:(id)sender{
    //Do something here here with the value selected using [pickerView date] to get that value
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    
    dateString = [dateFormatter stringFromDate:currentDate];
    [dateTextField setText:dateString];
    [dateTextField resignFirstResponder];
    [pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];
}

-(void)cancelDateButtonPressed:(id)sender{
    
    //    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    //    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    //    [dateTextField setText:[dateFormatter stringFromDate:datePickerView.date]];
    [dateTextField resignFirstResponder];
    [pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];
    //[currencyPickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];
}

#pragma mark------------------IBACtionDelegate--------------------------


- (IBAction)backButtonPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)addButtonPressed:(id)sender {
    folyAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    double walletBalance = [delegate.currentWallet.w_balance doubleValue];
    double amountInput = [amountTextField.text doubleValue];
    if([kindOfView isEqualToString:@"Add"]) {
        if ( ([expenseNameTextField.text isEqualToString:@""] ||
              [amountTextField.text isEqualToString:@""] ||
              [dateTextField.text isEqualToString:@""] ) ) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Incompleted adding!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [expenseNameTextField resignFirstResponder];
            [amountTextField resignFirstResponder];
        } else if (amountInput <= 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Invalid value of money!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [amountTextField setText:nil];
            [expenseNameTextField resignFirstResponder];
            [amountTextField resignFirstResponder];
        } else {
            if (amountInput > walletBalance) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Your wallet is not enough money!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
                [amountTextField setText:nil];
                [expenseNameTextField resignFirstResponder];
                [amountTextField resignFirstResponder];
            } else {
                currentPlan.p_startamount  = [NSNumber numberWithInt:[currentPlan.p_startamount intValue] - [amountTextField.text intValue]];

                if(![currentPlan.p_name isEqualToString:@"Chưa có kế hoạch"]){
            
                }
                delegate.currentWallet.w_balance = [NSNumber numberWithDouble:(walletBalance - amountInput)];
                [DataBaseAccess createExpenseWithname:expenseNameTextField.text andAmount:amountInput andDate:currentDate andNotes:noteTextField.text inPlan:currentPlan ofType:currentExpenseType];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"addExpense_OnSuccess" object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"expenseAdded" object:expenseNameTextField.text];
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
    } else {
        if ( ([expenseNameTextField.text isEqualToString:@""] ||
              [amountTextField.text isEqualToString:@""] ||
              [dateTextField.text isEqualToString:@""] ) ) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Incompleted editing!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [expenseNameTextField resignFirstResponder];
            [amountTextField resignFirstResponder];
        } else if ([amountTextField.text doubleValue] <= 0) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Invalid value of money!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            [amountTextField setText:nil];
            [expenseNameTextField resignFirstResponder];
            [amountTextField resignFirstResponder];
        } else {
            double firstAmount = [currentExpense.e_amount doubleValue];
            
            if ( (walletBalance + (firstAmount - amountInput)) < 0 ) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Your wallet is not enough money!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
                [amountTextField setText:nil];
                [expenseNameTextField resignFirstResponder];
                [amountTextField resignFirstResponder];
            } else {

                currentExpense.e_name = expenseNameTextField.text;
                currentExpense.eToExpenseType = currentExpenseType;
                currentExpense.e_amount = [NSNumber numberWithDouble:amountInput];
                currentExpense.e_date = currentDate;
                currentExpense.eToPlan = currentPlan;
                currentExpense.e_notes = noteTextField.text;
        
                delegate.currentWallet.w_balance = [NSNumber numberWithDouble:(walletBalance + (firstAmount - amountInput))];
                [DataBaseAccess saveData];
                [self.navigationController popViewControllerAnimated:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"addExpense_OnSuccess" object:nil];
            }
        }
    }

    
    
}
@end
